package com.raysdata.smartcity.tools;


import com.raysdata.smartcity.dao.RzBaseDao;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.runtime.RuntimeConstants;
import org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader;

/**
 * Created by kzhou on 2016/1/1.
 */
public class DaoGenerator {
    public static void go(RzBaseDao dao, String path, String table){
        VelocityEngine ve = new VelocityEngine();
        ve.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath");
        ve.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName());
        ve.init();
        Template dtoTpl = ve.getTemplate("com/raysdata/smartcity/tools/daoTpl.vm");
        VelocityContext ctx = new VelocityContext();

        String daoName = GeneratorUtil.toUpperCaseFirstOne(table.replace("yp_","")) + "Dao";
        String dtoClassName = GeneratorUtil.toUpperCaseFirstOne(table);
        String dtoArgumentName = GeneratorUtil.toLowerCaseFirstOne(table.replace("yp_",""));
        String pk = GeneratorUtil.toUpperCaseFirstOne(dao.getPKColNameByTableName(table));
        String insertSql = dao.makeSql4Insert(table);
        String updateSql = dao.makeSql4Update(table);
        String selectAllSql = dao.makeSql4SelectAll(table);
        String selectByIdSql = dao.makeSql4SelectById(table);
        String deleteSql = dao.makeSql4Delete(table);

        if(path!=null&&!path.equals("")){
            ctx.put("package","package com.raysdata.smartcity.dao."+path+";");
        }else{
            ctx.put("package","package com.raysdata.smartcity.dao;");
        }

        ctx.put("daoName",daoName.replace("Yp",""));
        ctx.put("dtoClassName",dtoClassName.replace("Yp",""));
        ctx.put("dtoArgumentName",dtoArgumentName);
        ctx.put("pk",pk);
        ctx.put("insertSql",insertSql);
        ctx.put("updateSql",updateSql);
        ctx.put("deleteSql",deleteSql);
        ctx.put("selectAllSql",selectAllSql);
        ctx.put("selectByIdSql",selectByIdSql);
        GeneratorUtil.merge(dtoTpl, ctx, GeneratorUtil.getPath("dao") +path+"/"+ daoName + ".java");
    }
}
